﻿module Sustainalytics.Universes {
    export class UniversesService implements IUniversesService {
        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: INotificationFactory;
        private staticObjects: IStaticObjects;
        private $location: ng.ILocationService;
        private $upload: any;

        constructor($q: ng.IQService, $http: ng.IHttpService, $location: ng.ILocationService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects, $upload) {
            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.staticObjects = staticObjects;
            this.$location = $location;
            this.$upload = $upload;
        }

        private filesUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/universesserv/api/v1/files";
        }

        private uploaderrorlogsUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/universesserv/api/v1/uploaderrorlogs";
        }

        public fileUpload(file: File, id: string): ng.IPromise<{}> {

            var ctx = this;
            var def = ctx.$q.defer();

            var reader = new FileReader();
            reader.onload = (data) => {
                return ctx.$upload.http({
                    method: (id) ? "PUT" : "POST",
                    url: ctx.filesUrl() + ((id) ? id : ""),
                    headers: { 'Content-Disposition': 'attachment; filename="' + file.name + '"', 'Content-Type': file.type, },
                    data: reader.result
                })
                    .progress(evt => { console.log('percent: ' + (100.0 * evt.loaded / evt.total)); })
                    .success((data, status, headers, config) => { def.resolve(data) });
            };
            reader.readAsArrayBuffer(file);
            return def.promise;
        }

        public getUploadErrorLogs(): ng.IPromise<Array<IUploadErrorLog>> {
            var ctx = this;
            var def = ctx.$q.defer();

            var promise = ctx.$http.get(ctx.uploaderrorlogsUrl());
            promise
                .success(data => { def.resolve(data); })
                .error(err => { ctx.showError(err); def.reject(); });
            return def.promise;
        }

        public isProcessingScheduled(): ng.IPromise<boolean> {
            var ctx = this;
            var def = ctx.$q.defer();

            var promise = ctx.$http.get(ctx.filesUrl(), { params: { isProcessing: true } });
            promise
                .success(data => { def.resolve(data); })
                .error(err => { ctx.showError(err); def.reject(); });
            return def.promise;
        }

        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjects.getMessageByInternalCode(err['code']));
        }
    }

    // register service with Tools Angular module
    angular.module('Sustainalytics.Universes').factory('UniversesService',
        ($q: ng.IQService, $http: ng.IHttpService, $location: ng.ILocationService, notificationFactory: INotificationFactory, staticObjects: IStaticObjects, $upload) =>
            new UniversesService($q, $http, $location, notificationFactory, staticObjects, $upload)
        );
}